package cn.lijiajia3515.cairo.auth.modules.role;

import cn.lijiajia3515.cairo.auth.domain.mongo.RoleMongo;
import cn.lijiajia3515.cairo.auth.modules.resource.ResourceConverter;
import cn.lijiajia3515.cairo.auth.modules.resource.ResourceTreeNode;
import cn.lijiajia3515.cairo.auth.modules.account.Account;
import cn.lijiajia3515.cairo.common.BaseConverter;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

public class RoleConverter extends BaseConverter {

	public static Role convert(RoleMongo m, Map<String, Integer> userNumMap, Map<String, Account> accountMap, RoleExtension extension) {
		Role.RoleBuilder<?, ?> builder = Role.builder().id(m.getId());
		Optional.of(extension.fields())
			.filter(x -> x.contains(RoleField.NAME))
			.flatMap(x -> Optional.ofNullable(m.getName()))
			.ifPresent(builder::name);

		Optional.of(extension.fields())
			.filter(x -> x.contains(RoleField.REMARK))
			.flatMap(x -> Optional.ofNullable(m.getRemark()))
			.ifPresent(builder::remark);

		Optional.of(extension.fields())
			.filter(x -> x.contains(RoleField.USER_NUM))
			.map(x -> Optional.ofNullable(m.getId()).filter(userNumMap::containsKey).map(userNumMap::get).orElse(0))
			.ifPresent(builder::userNum);

		Optional.of(extension.fields())
			.filter(x -> x.contains(RoleField.METADATA))
			.flatMap(x -> Optional.ofNullable(m.getMeta()))
			.map(x -> convert(x, accountMap))
			.ifPresent(builder::meta);

		return builder.build();
	}

	public static RoleV2 convert(RoleMongo m, Map<String, ResourceTreeNode> resources) {
		List<ResourceTreeNode> roleResources = m.getResources().stream().map(resources::get).filter(Objects::nonNull).collect(Collectors.toList());

		return RoleV2.builder()
			.id(m.getId())
			.name(m.getName())
			.remark(m.getRemark())
			.resources(ResourceConverter.tree(roleResources))
			.build();
	}
}
